import { AxiosRequestConfig } from "./types";
import { RequestKey } from "./static";
import { createAxiosServiceHandler } from "./lib";
import { AxiosInstance } from "axios";
import { inject } from "vue";
import { RequestHandler } from "./types";

/**
 *
 */
const requestPlugin = {
  install(app: any, options?: AxiosRequestConfig) {
    try {
      let handler: RequestHandler = createAxiosServiceHandler(options);
      app.config.globalProperties.$csrq = handler;
      app.provide(RequestKey, handler);
    } catch (err) {
      console.log(err);
    }
  },
};

const useRequest = (): RequestHandler => {
  let handler: RequestHandler = inject<RequestHandler>(RequestKey);
  if (handler === undefined) {
    throw new Error("inject error");
  } else {
    return handler;
  }
};

export { requestPlugin, useRequest };
